import CryptoJS from 'crypto-js';
import dayjs from 'dayjs';
export const to = (promise: Promise<any>): Promise<any[]> => {
    return new Promise((resolve) => {
        promise.then(
            (res) => resolve([res, null]),
            (err) => resolve([null, err]),
        );
    });
}

export const getCookie = (val: string) => {//获取x-csrf-token字段
    var arr, reg = new RegExp("(^| )" + val + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}

export function genSign(text: string) {
    // 密钥和iv需要安全地存储并同步到服务器端
    const SECRET_KEY = '9vApxLk5G3PAsJrM'; // 必须是32字节长的字符串
    const IV = 'FnJL7EDzjqWjcaY9'; // 必须是16字节长的字符串
    const key = CryptoJS.enc.Utf8.parse(SECRET_KEY);
    const iv = CryptoJS.enc.Utf8.parse(IV);

    const encrypted = CryptoJS.AES.encrypt(text, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });

    return encrypted.ciphertext.toString(); // 返回Base64编码的加密字符串
}

export function formatTime(date: string, format: string = "YYYY-MM-DD HH:mm:ss") {
    return dayjs(date).format(format);
}